﻿using System;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.Class;
using System.Collections.Generic;
namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class DispenseController : Controller
    {
        //
        // GET: /Dispense/


        #region Dispense

        public ActionResult Index()
        {
            var service = new DispenseService.DispenseServiceClient();
            return View(service.SelectDispense(new Models.ICM.Dispense { RecordStatus = "!D" }, new[] { "FromJobSite", "Project", "Warehouse", "RequestParcel" }));
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Dispense model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new DispenseService.DispenseServiceClient();
                    model.Code = CodeGenerate.GetNextCode(CodeGenerate.TransectionType.Dispense);
                    int id = service.Insert(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { id = id });
                }
                return View(model);
            }
            catch (Exception ex)
            {
                throw ex;
                //return View();
            }
        }
        
        public ActionResult Edit(int id)
        {
            var service = new DispenseService.DispenseServiceClient();
            var item = service.SelectDispense(new Models.ICM.Dispense { DispenseId = id, RecordStatus = "!D" }, new[] { "RequestParcel" }).FirstOrDefault();

            if (item == null)
            {
                return HttpNotFound();
            }
            ViewBag.State = "Edit";
            return View(item);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Dispense model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new DispenseService.DispenseServiceClient();
                    service.Update(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Index");
                }
                return Edit(model.DispenseId);
            }
            catch
            {
                return Edit(model.DispenseId);
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new DispenseService.DispenseServiceClient();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index");
            }
            catch
            {
                return Index();
            }
        }

        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new DispenseService.DispenseServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        #endregion

        #region DispenseDtl

        public ActionResult Details(int id)
        {
            int intRequestParcelId = 0;
            ViewBag.DispenseId = id;

            var service = new DispenseService.DispenseServiceClient();
            var itemDispense = service.SelectDispense(new Models.ICM.Dispense { DispenseId = id, RecordStatus = "!D" }, new[] { "FromJobSite", "Project", "Warehouse", "RequestParcel" }).FirstOrDefault();   
            if (itemDispense != null)
            {
                intRequestParcelId = itemDispense.RequestParcelId;
                ViewBag.ProjectId = itemDispense.ProjectId;
                ViewBag.ReqCode = itemDispense.RequestParcel.IcmReqCode;
                ViewBag.DispenseDate = itemDispense.DispenseDate;
                ViewBag.Jobsite = itemDispense.FromJobSite.Name;
                ViewBag.ProjectName = itemDispense.Project != null ? itemDispense.Project.Name : "ไม่ระบุ";
                ViewBag.DispenseName = itemDispense.DispenseName;
                ViewBag.RequestBy = itemDispense.RequestById;
                ViewBag.RequestStatus = itemDispense.RequestParcel.RecordStatus;
                ViewBag.RequestId = itemDispense.RequestParcelId;
            }

            return View();
        }

        [HttpPost]
        public ActionResult CreateDispense(string strType, int intItemId, int intWhId, int intReqQty,
            int intDispenseId, int intProjectId, string strPlace, int intReqDtlId, string strAssetCode)
        {
            try
            {
                var service = new DispenseService.DispenseServiceClient();
                //var serviceDispose = new DisposeService.DisposeServiceClient();

                string strJobSiteName = "";
                string strWarehouseName = "";

                var itemDispense = service.SelectDispense(new Models.ICM.Dispense { DispenseId = intDispenseId, RecordStatus = "!D" }, new[] { "FromJobSite", "Project", "Warehouse", "RequestParcel" }).FirstOrDefault();
                if (itemDispense != null)
                {
                    strJobSiteName = itemDispense.FromJobSite.Name;
                    strWarehouseName = itemDispense.Warehouse.Name;
                }

                var modelRequestDtl = service.SelectRequestParcelDtl(new Models.ICM.RequestParcelDtl { ReqDtlId = intReqDtlId, ResItemId = intItemId, RecordStatus = "!D" }, null).FirstOrDefault();
                int intJobSiteId = modelRequestDtl.JobsiteId;

                DispenseHistory modelDispenseHis = new DispenseHistory();
                MovementHistory modelMovementHis = new MovementHistory();


                int intProjExpId = service.GetProjExp(intProjectId);

                if (ModelState.IsValid)
                {
                    // วัสดุ
                    if (strType == "OS")
                    {
                        #region OS
                        var ListOffice = service.SelectOfficeSuppliesLot(new GERP.Models.ICM.OfficeSuppliesLot
                        {
                            ResItemId = intItemId,
                            WhId = intWhId,
                            RecordStatus = "!D"
                        }, null).Where(x => x.Quantity > 0).ToList().OrderBy(x => x.CreatedWhen);

                        var OfficeSuppliesLot = ListOffice
                            // .Where(x => x.ProjExpId == intProjExpId || x.ProjExpId == null)
                            .ToList();

                        var lenght = OfficeSuppliesLot.Count();
                        var qty = OfficeSuppliesLot.Select(x => x.Quantity).ToList();
                        var price = OfficeSuppliesLot.Select(x => x.Price).ToList();
                        var lot = OfficeSuppliesLot.Select(x => x.LotNo).ToList();
                        var officeId = OfficeSuppliesLot.Select(x => x.OfficeSuppliesLotId).ToList();

                        string strLotNo = "";
                        decimal decPrice = 0;
                        int intRem = 0;
                        int intOfficeId = 0;

                        for (int i = 0; i < lenght; )
                        {
                            do
                            {
                                intOfficeId = officeId[i];
                                strLotNo = lot[i];
                                decPrice = price[i];
                                intRem = Convert.ToInt32(qty[i]) - intReqQty;

                                    var modelOffice = service.SelectOfficeSuppliesLot(new GERP.Models.ICM.OfficeSuppliesLot
                                    {
                                        OfficeSuppliesLotId = intOfficeId,
                                        RecordStatus = "!D"
                                    }, null).FirstOrDefault();

                                    if (intRem <= 0)
                                    {
                                        // update qty[i] ของ lot[i] ให้เท่ากับ 0
                                        modelOffice.Quantity = 0;
                                        service.UpdateOfficeSupplies(modelOffice, Class.GimsMembership.CurrentEmpId);

                                        // InsrtyDispenseHistory
                                        modelDispenseHis.DispenseId = intDispenseId;
                                        modelDispenseHis.ResItemId = intItemId;
                                        modelDispenseHis.LotNo = strLotNo;
                                        modelDispenseHis.WhId = intWhId;
                                        modelDispenseHis.Quantity = intRem + intReqQty;
                                        modelDispenseHis.Price = decPrice;
                                        //modelDispenseHis.RefNo = ""; ยังไม่ทราบข้อมูลที่จะนำมาใส่
                                        service.InsertDispenseHistory(modelDispenseHis, Class.GimsMembership.CurrentEmpId);

                                        // จำนวนคงเหลือก
                                        intReqQty = Math.Abs(intRem);
                                    }
                                    else
                                    {
                                        intOfficeId = officeId[i];
                                        strLotNo = lot[i];
                                        decPrice = price[i];

                                        // update qty[i] ของ lot[i] ให้เท่ากับ 0
                                        modelOffice.Quantity = intRem;
                                        service.UpdateOfficeSupplies(modelOffice, Class.GimsMembership.CurrentEmpId);

                                        // InsrtyDispenseHistory
                                        modelDispenseHis.DispenseId = intDispenseId;
                                        modelDispenseHis.ResItemId = intItemId;
                                        modelDispenseHis.LotNo = strLotNo;
                                        modelDispenseHis.WhId = intWhId;
                                        modelDispenseHis.Quantity = intReqQty;
                                        modelDispenseHis.Price = decPrice;
                                        //modelDispenseHis.RefNo = ""; ยังไม่ทราบข้อมูลที่จะนำมาใส่
                                        service.InsertDispenseHistory(modelDispenseHis, Class.GimsMembership.CurrentEmpId);
                                    }
            
                                    i++;

                            } while (intRem < 0);
                            i++;
                            // update ที่ RequestParcelDetail ว่า จ่ายแล้ว
                            modelRequestDtl.DispenseStatus = "true";
                            service.UpdateRequestParcelDtl(modelRequestDtl, Class.GimsMembership.CurrentEmpId);
                        }
                        #endregion
                    }
                    // ครุภัณฑ์
                    else
                    {
                        #region A
                    //var ListAsset = service.SelectAsset(new GERP.Models.ICM.Asset
                    //    {
                    //        ResItemId = intItemId,
                    //        WhId = intWhId,
                    //        RecordStatus = "!D"
                    //        }, null).Where(x => x.JobSiteId == null).ToList().OrderBy(x => x.AssetId);

                    //var Asset = ListAsset.Where(x => x.ProjExpId == intProjExpId || x.ProjExpId == null).ToList();

                    //    var lenght = Asset.Count();
                    //    var qty = Asset.Select(x => x.Quantity).ToList();
                    //    var price = Asset.Select(x => x.Price).ToList();
                    //    var assetId = Asset.Select(x => x.AssetId).ToList();

                    //    int intQty = 0;
                    //    int intAssetId = 0;
                    //    double dblPrice = 0;
                        
                    //    for (int i = 0; i < lenght && i < intReqQty; i++)
                    //    {
                    //            intQty = qty[i];
                    //            intAssetId = assetId[i];
                    //            dblPrice = price[i];
                             
                    //                var modelAsset = service.SelectAsset(new GERP.Models.ICM.Asset
                    //                {
                    //                    AssetId = intAssetId,
                    //                    RecordStatus = "!D"
                    //                }, null).FirstOrDefault();
                    //                // Update Asset
                    //                modelAsset.Place = strJobSiteName;
                    //                modelAsset.JobSiteId = intJobSiteId; 
                    //                service.UpdateAsset(modelAsset, Class.GimsMembership.CurrentEmpId);

                    //                modelMovementHis.AssetId = intAssetId;
                    //                modelMovementHis.MoveQty = intQty;
                    //                modelMovementHis.SourceLocation = strWarehouseName;
                    //                modelMovementHis.DestinationLocation = strJobSiteName;
                    //                modelMovementHis.MoveRefNo = intDispenseId;
                    //                modelMovementHis.MovementType = "Disp";
                    //                service.InsertMovementHistory(modelMovementHis, Class.GimsMembership.CurrentEmpId);                         
                    //    }

                        var modelAsset = service.SelectAsset(new GERP.Models.ICM.Asset
                                    {
                                        AssetCode = strAssetCode,
                                        RecordStatus = "!D"
                                    }, null).FirstOrDefault();
                        // Update Asset
                        modelAsset.Place = strJobSiteName;
                        modelAsset.JobSiteId = intJobSiteId;
                        service.UpdateAsset(modelAsset, Class.GimsMembership.CurrentEmpId);

                        // insert ที่ MovementHistory
                        modelMovementHis.AssetId = modelAsset.AssetId;
                        modelMovementHis.MoveQty = 1;
                        modelMovementHis.SourceLocation = strWarehouseName;
                        modelMovementHis.DestinationLocation = strJobSiteName;
                        modelMovementHis.MoveRefNo = intDispenseId;
                        modelMovementHis.MovementType = "Disp"; // Disp หมายถึง จ่ายพัสดุ
                        service.InsertMovementHistory(modelMovementHis, Class.GimsMembership.CurrentEmpId);

                        // update ที่ RequestParcelDetail ว่า จ่ายแล้ว
                        modelRequestDtl.DispenseStatus = "true";
                        service.UpdateRequestParcelDtl(modelRequestDtl, Class.GimsMembership.CurrentEmpId);
                        #endregion
                    }

                    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Details", "Dispense", new { id = intDispenseId });
                    return Json(new { success = true, Url = redirectUrl });

                }
                return RedirectToAction("Details", intDispenseId);
            }
            catch
            {
            return View();
            }            
        }


        #endregion

        #region GetData

        public JsonResult GetRequestParcel(int id)
        {
            var service = new DispenseService.DispenseServiceClient();
            var item = service.SelectRequestParcel(new Models.ICM.RequestParcel { ReqParcelId = id, RecordStatus = "!D" }, new[] { "Employee", "Jobsite", "Project", "WarehousePermit", "WarehousePermit.Warehouse" }).FirstOrDefault();
            
            string strReqBy = item.Employee.FirstName + "  " + item.Employee.LastName;
            string strWarehouse = item.WarehousePermit.Warehouse.Name;
            string strJobSite = item.JobSite.Name;
            string strProject = item.Project != null ? item.Project.Name : "ไม่ระบุ";
            string strApproveBy = item.ApprovedBy.ToString();
            string strApproveWhen = item.ApprovedDate.ToString();
            string strReqName = item.RequestName;

            int? intReqBy = item.RequestBy;
            int intWhId = item.WarehousePermit.WhId;
            int? intJobSiteId = item.JobSiteId;
            int? intProjectId = item.ProjectId;

            return this.Json(
                new
                {
                    ReqName = strReqName,
                    ReqBy = strReqBy,
                    Warehouse = strWarehouse,
                    JobSite = strJobSite,
                    Project = strProject,
                    ApproveBy = strApproveBy,
                    ApproveWhen = strApproveWhen,

                    ReqById = intReqBy,
                    WarehouseId = intWhId,
                    JobSiteId = intJobSiteId,
                    ProjectId = intProjectId
                }
                , JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetSumQuantity(int intItemId, int intWhId, int intProjectId, string Type)
        {
            var service = new DispenseService.DispenseServiceClient();
            int sumQty = service.GetSumQuantity(Type, intItemId, intProjectId, intWhId);
            return this.Json(
                new
                {
                    SumQuantity = sumQty
                }
                , JsonRequestBehavior.AllowGet);
        }


        public JsonResult SearchAsset(string strAssetCode, int intWhId)
        {
            var service = new DispenseService.DispenseServiceClient();

            var asset = service.SelectAsset(new Asset { 
                RecordStatus = "!"+Models.SYS.RecordStatus.DeletedStatus,
                AssetCode = strAssetCode,
                WhId = intWhId
            }, null).Where(x => x.JobSiteId == null).ToList();

            string strAsset = string.Empty;
            if (asset.Count > 0)
            {
                strAsset = "มีครุภัณฑ์ชิ้นนี้ในคลัง สามารถทำการจ่ายได้";
            }
            else
            {
                strAsset = "อาจจะไม่มีครุภัณฑ์ชิ้นนี้อยู่ในคลัง หรืออาจจะทำการจ่ายครุภัณฑ์ชิ้นนี้ไปแล้ว";
            }

            return this.Json(
                new
                {
                    message = strAsset
                }
                , JsonRequestBehavior.AllowGet);
        }


        #endregion

        #region Report

        public void DispensReport(int intDispenseId)
        {
            var service = new DispenseService.DispenseServiceClient();
            var model = service.DispenstReportHead(intDispenseId);
            //var model1 = service.SelectDispense(new Dispense() { DispenseId = intDispenseId, RecordStatus = "!" + RecordStatus.DeletedStatus }
            //    , new[] { "", "" }).ToList();
            var dics = service.DispensReportDtls(intDispenseId).ToList();
            MailMerge mailMerge = new MailMerge();
            Dictionary<string, string> fields = new Dictionary<string, string>();

            fields.Add("EmpName", model[0]);
            fields.Add("PosName", model[1]);
            fields.Add("JobSiteName", model[2]);
            fields.Add("SubJobSiteName", model[3]);

            string strTemplatePath = Server.MapPath("~/Templates/ใบรับมอบพัสดุ.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("ใบรับมอบพัสดุ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null, dics, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                if (true)
                {
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                }
                Response.End();
            }
         }

        #endregion
    }
}
